/*
 * [程序名称] Weather auto sender
 * [参考资料] http://code.google.com/p/auto-weather-sender/ 
 * [开源协议] Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.joe.weather.service;

import java.util.Calendar;
import java.util.TimeZone;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;

import com.joe.weather.MainActivity;
import com.joe.weather.R;
import com.joe.weather.WeatherApplication;
import com.joe.weather.tool.PreferenceUtil;
import com.joe.weather.tool.SMSUtil;
import com.joe.weather.tool.WeatherUtil;

public class WeatherService extends Service implements Runnable
{
	private final static String TAG = WeatherService.class.getSimpleName();
	
	private static final long repeatTime = 24*60*60*1000;
//	private static final long repeatTime = 3*60*1000;
	
	SharedPreferences sp = null;
	
	WeatherApplication application = null;
	
	boolean systemEnable;
	boolean firstTimeLaunchSystem;
	
	@Override
	public void onCreate()
	{
		super.onCreate();
		
		application = (WeatherApplication) getApplicationContext();
		
		sp = PreferenceManager.getDefaultSharedPreferences(this);
		
		Log.e(TAG, "onCreate.........");
	}

	@Override
	public void onStart(Intent intent, int startId)
	{
		super.onStart(intent, startId);
		Log.e(TAG, "onStart.........");
		
		Bundle bundle = null;
		if(intent != null)
		{
			bundle = intent.getExtras();
		}
		
		boolean flag = bundle!=null?bundle.getBoolean(application.REPEATFLAG):false;
		application.setWeatherServiceRepeatFlag(flag);
		
		new Thread(this).start();
	}
	
	@Override
	public void run()
	{
		Log.e(TAG, "Running into WeatherService.........");
		
		systemEnable = sp.getBoolean("systemSwitch", true);
		firstTimeLaunchSystem = sp.getBoolean("FIRST_TIME_LAUNCH_SYSTEM", true);
		
		if(systemEnable && !firstTimeLaunchSystem)
		{
			sendWeatherSMS();
		}
		
		if(application.isWeatherServiceRepeatFlag() || firstTimeLaunchSystem)
		{
			proposeNextLaunch();
			application.setWeatherServiceRepeatFlag(false);
		}
		
		if(firstTimeLaunchSystem)
		{
			Editor editor = sp.edit();
			editor.putBoolean("FIRST_TIME_LAUNCH_SYSTEM", false);
			editor.commit();
		}
		
		// stop service
		stopSelf();
	}
	
	private void sendWeatherSMS()
	{
		Log.e(TAG, "Begin to send sms.........");
		sp = PreferenceManager.getDefaultSharedPreferences(this);
		String currentCityCode = sp.getString("cityName", "101280101");
		
		PreferenceUtil preUtil = new PreferenceUtil(this);
		String callName = preUtil.getCurrentCallName();
		String cityName = preUtil.getCurrentCityName(currentCityCode);
		
		final String smsDest = sp.getString(application.CELLPHONE_NUMBER, application.destNumber);
		final String smsContent = WeatherUtil.getSMSMessage(callName, currentCityCode, cityName);
		
		if(!"".equals(smsContent))
		{
			SMSUtil.sendMessage(getBaseContext(), smsDest, smsContent);
			
			showNotification(true, callName, cityName);
		}
		else
		{
			showNotification(false, callName, cityName);
		}
	}
	
	private void proposeNextLaunch()
	{
		final int sendAtHour = sp.getInt(application.SEND_AT_HOUR, application.DEFAULT_SEND_AT_HOUR);
		
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeZone(TimeZone.getTimeZone("GMT+8"));
		if(sendAtHour <= calendar.get(Calendar.HOUR_OF_DAY))
			calendar.add(Calendar.DATE, 1);
		calendar.set(Calendar.HOUR_OF_DAY, sendAtHour);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
		
//		Calendar calendar = Calendar.getInstance();
//		calendar.setTimeZone(TimeZone.getTimeZone("GMT+8"));
//		calendar.add(Calendar.MINUTE, 1);
		
		Intent intent = new Intent();
		intent.setClass(this, WeatherService.class);
		PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, 0);
		
		AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
		alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, 
				calendar.getTimeInMillis(), repeatTime, pendingIntent);
		Log.e(TAG, "The weather will launch next time at: " + calendar.getTime().toLocaleString());
	}

	@Override
	public void onDestroy()
	{
		super.onDestroy();
	}

	@Override
	public IBinder onBind(Intent intent)
	{
		return null;
	}
	
	private void showNotification(boolean successFlag, String callName, String cityName)
	{
		NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); 
		Notification notification = new Notification(R.drawable.weather, "Hello,there!", System.currentTimeMillis()); 
		notification.defaults = Notification.DEFAULT_ALL;
		notification.flags = Notification.FLAG_AUTO_CANCEL;
		Intent intent = new Intent(this.getBaseContext(), MainActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK); 
		PendingIntent contentIntent = PendingIntent.getActivity(
				getBaseContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		
		if(successFlag)
		{
			notification.setLatestEventInfo(getBaseContext(), "成功！", "给猪头发送天气预报--成功！", contentIntent);
		}
		else
		{
			notification.setLatestEventInfo(getBaseContext(), "失败！", "给猪头发送天气预报--失败！", contentIntent);
		}
		manager.notify(0, notification);
	}
	
}
